package com.ruoyi.framework.interceptor;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.boc.config.SSOPConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.JSONUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.BOCCryptography;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * SSOP单点登录拦截处理
 */
@Component
public class SSOPLogHandleInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(SSOPLogHandleInterceptor.class);

    @Resource
    private SSOPConfig ssopConfig;

    @Resource
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("进入ssop拦截器");
        //只针对单点登录的url拦截处理
        String returnUrl = ssopConfig.getReturnUrl();
        if (StringUtils.isNotEmpty(returnUrl) && request.getRequestURI().endsWith(returnUrl.substring(returnUrl.lastIndexOf("/") + 1))) {
            String sessionid = request.getParameter("sessionid");
            // 目前暂使用配置文件的方式统一配置
            if (request.getUserPrincipal() == null && StringUtils.isEmpty(sessionid)) {
                logger.info("SSOP第一次拦截，请求方式：{}", request.getMethod());
                String url = URLEncoder.encode(ssopConfig.getReturnUrl(), "UTF-8");
                //这里不会改变POST方式
//                response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
//                response.setHeader("Location", ssopProperty.getRedirectLocation() + "?returnurl=" + url + "&sysid="
//                        + ssopProperty.getSysId());

                //这里需要get请求方式  ajax请求无法重定向
//                response.sendRedirect(ssopProperty.getRedirectLocation() + "?returnurl=" + url + "&sysid=" +
//                ssopProperty.getSysId());

                //需要重定向
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", true);
                resultMap.put("code", 10011);
                resultMap.put("data",
                        ssopConfig.getRedirectLocation() + "?returnurl=" + url + "&sysid=" + ssopConfig.getSysId());
                String json = JSONUtils.serialize(resultMap);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(json);
                response.flushBuffer();
                return false;
            } else {
                logger.info("SSOP第二次拦截，请求方式：{}", request.getMethod());
                logger.info("SSOP拦截器获取的sessionid为：{}", sessionid);
                JSONObject resultJson = new JSONObject();
                resultJson.put("result", -1);
                resultJson.put("message", "SSOP请求MIM的接口异常，请联系管理员");
                try {
                    String result = BOCCryptography.doGet(ssopConfig.getMimUrl(), ssopConfig.getSysId(),
                            ssopConfig.getpKey(), sessionid);
                    logger.info("SSOP请求MIM的接口返回result：{}", result);
                    resultJson = JSONObject.parseObject(result);
                } catch (Exception e) {
                    logger.error("SSOP请求MIM的接口失败：{}", e.getMessage());
                }
                if (0 == resultJson.getInteger("result")) {
                    //成功
                    String userNo = resultJson.getString("userid");
                    //redisCache.setCacheObject("ssop_login_key" + sessionid, userNo);
                    CacheUtils.put(CacheConstants.SSOP_LOGIN,"ssop_login_key"+sessionid, userNo);
                    //System.out.println("put:"+"ssop_login_key"+sessionid);
                    //重定向
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("username", userNo);
                    resultMap.put("success", true);
                    resultMap.put("isSSOP", true);
                    resultMap.put("sessionid", sessionid);
                    String json = JSONUtils.serialize(resultMap);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().print(json);
                    response.flushBuffer();
                    return false;
                } else {
                    //接口请求失败
                    logger.error("SSOP请求接口失败：{}", resultJson.getString("message"));
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("code", 401);
                    resultMap.put("msg", resultJson.getString("message"));
                    String json = JSONUtils.serialize(resultMap);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().print(json);
                    response.flushBuffer();
                    return false;
                }
            }

            //模拟admin用户登录
//            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/admin/login?username=" + "admin" +
//            "&password=" + "L249XCwyXb/zfMWiG4/Hgb29wpk5jKzDvcuu8B10B7c=" + "&frontDecrypt=false");
//            requestDispatcher.forward(request, response);
//            return false;
            //模拟接口错误信息
//            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("code", 401);
//            resultMap.put("msg", "接口不对");
//            String json = JSONUtils.serialize(resultMap);
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().print(json);
//            response.flushBuffer();
//            return false;

        }
        return true;
    }


}

